<?php

namespace App\Admin\Controllers;

use App\Models\Administrator;
use App\Models\DispatchFreeLog;
use App\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;

class DispatchFreeLogController extends Controller
{
    use ModelForm;

    private $header = '分配日志';
    private $description = '分配免费券';

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description($this->description);

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header($this->header);
            $content->description($this->description);

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description($this->description);

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(DispatchFreeLog::class, function (Grid $grid) {
            $grid->disableRowSelector();
            $grid->disableActions();

            if (Admin::user()->type === Administrator::TEAM_LEADER) {
                $grid->model()->where('team_leader_id', Admin::user()->team_id);
            }
            $grid->teamLeader()->name('管理员');
            $grid->user()->name('用户');
            $grid->num('分配数量');

            $grid->created_at('创建时间');
            $grid->filter(function ($filter) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
            });
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(DispatchFreeLog::class, function (Form $form) {
            $teamLeader = Admin::user()->id;
            $users = User::query()->where('team_id', $teamLeader->team->id)->pluck('phone_number', 'id');
            $form->hidden('team_leader_id')->value($teamLeader->id);
            $form->select('用户')->options($users);
            $max = (int)$teamLeader->team->free_times;
            $form->number('数量')->max($max);
            $form->display('created_at', 'Created At');
        });
    }
}
